<?php
/**
 * Created by PhpStorm.
 * User: ari
 * Date: 10/6/14
 * Time: 2:46 PM
 */
namespace BC\Games\Holdem;

class Cards
{
	const COUNT = 52;
	const TOTAL = 6786;

	//const ACE           = 0x10;
	const TWO           = 0x20;
	const THREE         = 0x30;
	const FOUR          = 0x40;
	const FIVE          = 0x50;
	const SIX           = 0x60;
	const SEVEN         = 0x70;
	const EIGHT         = 0x80;
	const NINE          = 0x90;
	const TEN           = 0xA0;
	const JACK          = 0xB0;
	const QUEEN         = 0xC0;
	const KING          = 0xD0;
	const ACE           = 0xE0;

	const NUMBER_MASK   = 0xF0;
	const NUMBER_DIV    = 0x10;

	const CLUBS         = 0x01;
	const DIAMONDS      = 0x02;
	const HEARTS        = 0x03;
	const SPADES        = 0x04;
	const SUIT_MASK     = 0x07;

	// Static

	public static function getSuitChar($card) {
		switch($card & self::SUIT_MASK) {
			case self::CLUBS:
				return '♣';
			case self::DIAMONDS:
				return '♦';
			case self::HEARTS:
				return '♥';
			case self::SPADES:
				return '♠';
		}
		throw new \InvalidArgumentException("Invalid card suit");
	}

	public static function printCards($cards) {
		$print = null;
		foreach((array)$cards as $card) {
			$num = $card & self::NUMBER_MASK;
			switch($num) {
				case self::ACE: $num = 'A'; break;
				case self::JACK: $num = 'J'; break;
				case self::QUEEN: $num = 'Q'; break;
				case self::KING: $num = 'K'; break;
				default: $num = $num / self::NUMBER_DIV;
			}
			$char = self::getSuitChar($card);
			$print = ($print ? $print . ', ' : '') . $num . $char;
		}
		return $print;
	}

	public static function sort(&$cards) {
		usort($cards, function($card1, $card2) {
			if($card1 === $card2)
				throw new \Exception("Same card found twice during sorting: " . $card1);
			return $card1 - $card2; // Numbers match, compare suits
		});
	}
}